<?php
/**
 * Created by PhpStorm.
 * User: 69548
 * Date: 2018/8/2
 * Time: 17:36
 */

namespace app\wap\controller;


use  app\wap\model\Order as M;
use think\Db;
use  app\wap\controller\Wxpay;

class Order1 extends Basewap
{
    //下单
        public function index(){

            $m=new M();
           $post=request()->post();
            if ($post['totalPrice']==0){
                $shu=[
                    'code'=>101,
                    'msg'=>'免费商品不能单独购买 价格为0 不能下单',
                ];
                echo json_encode($shu); die;
            }


//            dump($post);
            $goods=db('goods')->where('goods_id',$post['goods_id'])//获取商品
            ->field('starttime,endtime,tag_id,show,alltravellermessage,code')
                ->find();
            $where['isdelete']=0;
            $where['order_status']=[['NEQ',6],['NEQ',7,'or']];//订单查询条件
            $da=[];
            $shu=[];
            if ($goods['show']=1){
                $maiqu= db('order')//获取订单
                ->where('goods_id',$post['goods_id'])
                    ->where($where)
                    ->where('travel_date',$post['buyDay'])
                    ->select();

                foreach ($maiqu as $k){
                    $shengyu=db('orderperson')->where('order_id',$k['order_id'])->select();
                    $ce = db('person')//获取普通商品规格属性
                    ->where('specs_id',$post['specs_id'])
                        ->where('person_status', 1)
                        ->select();
                    foreach ($ce as $v){
                        foreach ($shengyu as $j){
                            if ($j['person_name'] === $v['person_name']){

                                foreach ($post['personArr'] as $s){
                                    $person_num = $v['person_num'] - ($j['person_num']+$s['person_num_buy']);
                                    if ($person_num<0){
                                        $tishi=$v['person_name'].'数量库存不足！';
                                        $shu=[
                                            'code'=>101,
                                            'msg'=>$tishi,
                                            'data'=>''
                                        ];
                                        echo json_encode($shu); die;

                                    }
//                                }
                                }
                            }
                        }

                    }

                }


            }

            $mk=model('Marketing')//获取活动
            ->where('goods_id',$post['goods_id'])
                ->where('mk_status',1)
                ->find();

            $str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            //1.获取字符串的长度
            $length = strlen($str)-1;
            //2.字符串截取开始位置
            $start=rand(0,$length);

//4.随机截取字符串，取其中的一部分字符串
            $A=substr($str, $start,1);
           $order_no=$A. date('Ymd').rand('5','99999');
            $shu=[];
            // 启动事务
            Db::startTrans();
            try{
//                $member=db('member')->where('member_id',$post['member_id'])->find();
                $order_ascription=1;
                $mem=db('member')->where('member_id',$post['member_id'])->field('member_pcode')->find();
                    if ($goods['show']==2){

                    if ($goods['alltravellermessage']==1){
                        $order_ascription=3;
                    }else{
                        $order_ascription=2;
                    }
                    }else{

                        $order_ascription=1;

                    }
                        $dingdan=$m->where('member_id',$post['member_id'])->where('finished_condition',1)->where('isdelete',0)->order('creattime desc')->find();
                        $shujian=  time()-$dingdan['creattime']   ;
                        if ($shujian<1000){
                            $shu=[
                                'code'=>0,
                                'msg'=>'有订单还没有完善 前往我的订单查看',
                                'data'=>'1'
                            ];
                            return json_encode($shu);
                        }

                        $pos=[];
                        foreach ($post['personArr'] as $v){
                            if ($v['person_num_buy']!=0){
                                $pos[]=[
                                    'person_name'=>$v['person_name'],
                                    'person_num'=>$v['person_num_buy'],
                                    'person_price'=>$v['person_price'],
                                    'chuxing'=>$post['buyDay'],
                                    'person_id'=>$v['person_id']
                                ];
                            }
                        }

                        $order_id= $m->insertGetId([
                            'order_no'=>$order_no,
                            'goods_id'=>$post['goods_id'],//商品id
                            'member_id'=>$post['member_id'],//会员id
                            'original_money'=>$post['totalPrice'],//交易金额
                            'fold_money'=>$post['totalPrice'],//交易金额
                            'add_integral'=>$post['integral'],//购买获得的积分
                            'creattime'=>time(),//下单时间
                            'travel_date'=>$post['buyDay'],//出行时间
                            'totalnum'=>$post['totalNum'],//购买数量
                            'specs_id'=>$post['specs_id'],//规格id
                            'finished_condition'=>1,//完成状况
                            'member_pcode'=>!empty($mem['member_pcode'])?$mem['member_pcode']:null,//完成状况
                            'orderperson'=>json_encode($pos),//完成状况
                            'order_ascription'=>$order_ascription,//订单归属
                            'code'=>$goods['code'],//订单归属
                            'grade'=>$post['code']//订单归属
                        ]);




                $shu=[
                    'code'=>0,
                    'msg'=>'下单成功',
                    'data'=>[
                        'order_no'=>$order_no,
                        'order_id'=>$order_id
                    ]
                ];

                // 提交事务
                Db::commit();


            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $shu=[
                    'code'=>101,
                    'msg'=>$e->getMessage(),
                    'error'=>$e->getMessage()
//                    ‘'data'=>$data
                ];

            }

            return json_encode($shu);
        }
//        查询未完善订单
        public function determine(){//确定订单

           $order_id= input('order_id');
            $shu=[];
            $m=new M();
            Db::startTrans();
            try{
          $order= $m
              ->alias('o')
              ->where('o.order_id',$order_id)
                ->join('goods a','a.goods_id=o.goods_id')
              ->field('a.goods_id,a.goods_name as poi_name,a.goods_image,o.travel_date,o.original_money,o.order_id,o.order_no,a.show,o.orderperson,o.order_ascription')
              ->find();
                    $img=  !empty($order['goods_image'])?explode(',',$order['goods_image']):'';
                    if (!empty($img[1])){
                        $order['goods_image']=$img[1] ;
                    }
//
//                }
                $ren=[];
if (empty($order['orderperson'])){
    $ren=db('orderperson')->where('order_id',$order['order_id'])->field('id,person_name,person_num')->select();
}else{
    $ren=json_decode($order['orderperson'],true);
    unset($order['orderperson']);
//    dump($ren);
}
                $order['person']=$ren;


                Db::commit();
                $shu=[
                    'code'=>0,
                    'msg'=>'查询成功',
                    'data'=>$order
                ];
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $shu=[
                    'code'=>0,
                    'msg'=>'查询失败',
                    'error'=>$e->getMessage()
//                    ‘'data'=>$data
                ];

            }

            return json_encode($shu);

        }

//        完善订单提交
        public function submit(){

          $post=  request()->post();
            $shu=[];
            $data=[];
          $m=new  M();
          $od=$m->where('order_id',$post['order_id'])->find();
          if (!empty($od['updatetime'])){
              $shu=[
                  'code'=>305,
                  'msg'=>'请不要重复提交订单',
              ];

              return json_encode($shu);
              die();
          }

          if ($od['order_ascription']==2||$od['order_ascription']==3){

              $posts=[];
              $code= db('goods')->where('goods_id',$od['goods_id'])->find();
              $pos=json_decode($od['orderperson'] ,true);
              $data['order']=$post['order_id'];//订单流水
              $data['time']=$od['travel_date'];
//            $currencyCode=$this->currencyCode;
              $data['code']=$code['code'];  //产品code
              $data['tourGradeCode']=$od['grade'];  //旅游等级 商品详情获取 tourGrades
              $data['orderuser']=[  //下蛋人信息- -
                  'firstname'=>$post['contact_xing'],  //名
                  'surname'=>$post['contact_ming'],  //姓
                  'Phone'=>$post['phone'], //必填
                  'email'=>$post['e_mail'],
              ];
              foreach ($pos as $v){
                  $datas['bandid'][$v['person_id']]= $v['person_num'];
              }
              //虚假人员
              $alluser=array_sum($datas['bandid']);
              foreach ($datas['bandid'] as $k=>$v){
                  for($i=0;$i<$v;$i++){
                      if ($i==0 && $k==1){
                          $tempList=[  //领班人/领头人
                              'leadTraveller'=>true,
                              'bandId'=>$k,
                              'firstname'=>$post['contact_xing'],
                              'surname'=>$post['contact_ming'],
                          ];
                      }else{
                          $tempList=[  //领班人/领头人
                              'bandId'=>$k,
                              'firstname'=>$post['contact_xing'].$alluser--,
                              'surname'=>$post['contact_ming'],
                          ];
                      }

                      $data['bandiduser'][]=$tempList;
                  }
              }
          }
            Db::startTrans();
            try{

                $coupon= !empty($post['coupon_id'])?$post['coupon_id']:0;
                if ($coupon!=0){
                    db('coupondetails')->where('id',$coupon)->update([
                        'usestatus'=>1
                    ]);
                }

          $m->where('order_id',$post['order_id'])->Update([
              'finished_condition'=>0,
              'wechat_number'=>$post['wechat_number'],//微信号
              'phone'=>$post['phone'],//手机号
              'fold_money'=>$post['fold_money'],//折扣后的金额
              'updatetime'=>time(),//更新时间
              'cost_ticket_id'=>$coupon,//使用优惠券的id
              'contact_xing'=>$post['contact_xing'],//xing
              'contact_ming'=>$post['contact_ming'],//ming
              'remarks'=>$post['remarks'],//备注
              'e_mail'=>$post['e_mail'],//邮箱
              'order_subsidiary'=>json_encode($data),//邮箱
          ]);
                Db::commit();
                $shu=[
                    'code'=>0,
                    'msg'=>'订单ok',
                ];

            } catch (\Exception $e) {
                Db::rollback();

                $shu=[
                    'code'=>101,
                    'msg'=>'失败',
                    'error'=>$e->getMessage()
//                    ‘'data'=>$data
                ];
            }




return json_encode($shu);


        }




}